'use client';

import { Form, Table, Card, Space, Divider } from '@douyinfe/semi-ui';
import type { ColumnProps } from '@douyinfe/semi-ui/lib/es/table';
import { useContext, useState, type ReactNode } from 'react';
import FlowSelectCard from './FlowSelectCard';
import clsx from 'clsx';
import type { Parameter } from '@/app/api/plans/route';
import type { FlowVO } from '@/app/api/flows/route';
import { sendDifyRequest } from '@/services/dify';
import type { FetchResponse } from 'ofetch';
import RemovalTable from './RemovalTable';
import ActionCard from '@/components/plans/generate/ActionCard';
import { DocxContext } from '@/contexts/DocxContext';

interface Props {
  className?: string;
  children?: ReactNode;
  onSubmit?: ({
    parameters,
    request,
    values,
  }: {
    parameters: Parameter[];
    request: any;
    values: any;
  }) => void;
  getFormApi?: ((formApi: any) => void) | undefined;
}

export default function PresaleTemplate({
  getFormApi,
  className,
  onSubmit,
  children,
}: Props) {
  const [designFlow, setDesignFlow] = useState<number>(1000);
  const [selectedFlow, setSelectedFlow] = useState<string | number>('');
  const [flows, setFlows] = useState<FlowVO[]>();
  const { docxRef } = useContext(DocxContext);

  const columnsMap = {
    污染物: '32',
    pH: 'ph',
    'CODcr（mg/L）': 'codcr',
    'BOD5（mg/L）': 'bod5',
    'SS（mg/L）': 'ss',
    'NH3-N（mg/L）': 'nh3n',
    'TN（mg/L）': 'tn',
    'TP（mg/L）': 'tp',
    '动植物油（mg/L）': 'oilGrease',
    '总大肠杆菌群数（个/L）': 'coliformTotal',
  };

  const handleSelectChange = (
    value: string | number | any[] | Record<string, any> | undefined
  ) => {
    setSelectedFlow(value as string);
  };

  const handleAllFlows = (flows: FlowVO[]) => {
    setFlows(flows);
  };

  const tableColumns: ColumnProps[] = [
    '污染物',
    'pH',
    'CODcr（mg/L）',
    'BOD5（mg/L）',
    'SS（mg/L）',
    'NH3-N（mg/L）',
    'TN（mg/L）',
    'TP（mg/L）',
    '动植物油（mg/L）',
    '总大肠杆菌群数（个/L）',
  ].map((item, i) => {
    if (i === 0) {
      return {
        render: (text) => {
          return (
            <div className="whitespace-nowrap py-2 text-center font-semibold text-gray-700">
              {text.name}
            </div>
          );
        },
      };
    } else if (i === 1) {
      return {
        render: (text, record, index) => {
          if (index === 0) {
            return {
              props: {
                colSpan: 9,
              },
              children: (
                <div className="flex items-center justify-center bg-blue-50 py-3">
                  <span
                    className="mr-1 text-xl font-bold"
                    style={{
                      color: 'var(--semi-color-primary)',
                    }}
                  >
                    {designFlow}
                  </span>
                  <span className="font-medium text-gray-600">m³/d</span>
                </div>
              ),
            };
          }
          if (index === 1) {
            return {
              props: {
                colSpan: 9,
              },
              children: (
                <div className="flex items-center justify-center bg-green-50 py-3">
                  <span className="mr-1 text-gray-700">q=</span>
                  <span
                    className="mx-1 font-bold"
                    style={{
                      color: 'var(--semi-color-primary)',
                    }}
                  >
                    {(designFlow / 24).toFixed(2)}
                  </span>
                  <span className="mx-1 text-gray-600">
                    m³/h（每天运行24小时），取整
                  </span>
                  <span
                    className="ml-1 font-bold"
                    style={{
                      color: 'var(--semi-color-primary)',
                    }}
                  >
                    {Math.ceil(designFlow / 24)}
                  </span>
                  <span className="ml-1 text-gray-600">m³/h</span>
                </div>
              ),
            };
          }
          if (index === 2) {
            return (
              <div className="bg-gray-50 py-2 text-center font-medium">pH</div>
            );
          }

          if (index === 3) {
            return (
              <div className="px-2 py-1">
                <Form.Input
                  field="phIn"
                  defaultValue="6～9"
                  noLabel
                  size="small"
                  style={{ borderRadius: '6px' }}
                  rules={[
                    {
                      required: true,
                      message: '请输入参数',
                      min: 0,
                    },
                  ]}
                />
              </div>
            );
          }

          if (index === 4) {
            return (
              <div className="px-2 py-1">
                <Form.Input
                  defaultValue={'6～9'}
                  field="phOut"
                  noLabel
                  size="small"
                  style={{ borderRadius: '6px' }}
                  rules={[
                    {
                      required: true,
                      message: '请输入参数',
                      min: 0,
                    },
                  ]}
                />
              </div>
            );
          }
        },
      };
    } else {
      return {
        render: (text, record, index) => {
          if (index === 0 || index === 1) {
            return {
              props: {
                colSpan: 0,
              },
              children: null,
            };
          }

          if (index === 2) {
            return (
              <div className="bg-gray-50 py-2 text-center text-sm font-medium">
                {item}
              </div>
            );
          }

          if (index === 3) {
            return (
              <div className="px-2 py-1">
                <Form.Input
                  field={columnsMap[item as keyof typeof columnsMap] + 'In'}
                  noLabel
                  size="small"
                  style={{ borderRadius: '6px' }}
                  rules={[
                    {
                      required: true,
                      message: '请输入参数',
                      min: 0,
                    },
                  ]}
                />
              </div>
            );
          }

          if (index === 4) {
            return (
              <div className="px-2 py-1">
                <Form.Input
                  addonBefore="≤"
                  field={columnsMap[item as keyof typeof columnsMap] + 'Out'}
                  noLabel
                  size="small"
                  style={{ borderRadius: '6px' }}
                  rules={[
                    {
                      required: true,
                      message: '请输入参数',
                      min: 0,
                    },
                  ]}
                />
              </div>
            );
          }
        },
      };
    }
  });

  const listData = [
    {
      key: '1',
      name: '设计水量',
    },
    {
      key: '2',
      name: '设计处理量',
    },
    {
      key: '3',
      name: '污染物',
    },
    {
      key: '4',
      name: '进水浓度',
    },
    {
      key: '5',
      name: '出水浓度',
    },
  ];

  const handleSubmit = async (values: any) => {
    console.log('进入提交函数，values:', values);
    const flow = flows?.find((item) => item._id === selectedFlow);

    const result: Parameter[] = [];

    const requests = [
      {
        requester: () => {
          const ctrl1 = new AbortController();
          return sendDifyRequest(
            {
              query: '生成设计方案',
              auto_generate_name: true,
              inputs: {
                service: 'removal',
                water: values.designFlowRate,
                gongyi: flow?.aiAnalysisText,
                shejicanshu: JSON.stringify({
                  污染物: [
                    {
                      指标: 'pH',
                      进水浓度: values.phIn,
                      出水浓度: values.phOut,
                    },
                    {
                      指标: 'CODcr（mg/L）',
                      进水浓度: values.codcrIn,
                      出水浓度: values.codcrOut,
                    },
                    {
                      指标: 'BOD5（mg/L）',
                      进水浓度: values.bod5In,
                      出水浓度: values.bod5Out,
                    },
                    {
                      指标: 'SS（mg/L）',
                      进水浓度: values.ssIn,
                      出水浓度: values.ssOut,
                    },
                    {
                      指标: 'NH3-N（mg/L）',
                      进水浓度: values.nh3nIn,
                      出水浓度: values.nh3nOut,
                    },
                    {
                      指标: 'TN（mg/L）',
                      进水浓度: values.tnIn,
                      出水浓度: values.tpOut,
                    },
                    {
                      指标: 'TP（mg/L）',
                      进水浓度: values.tpIn,
                      出水浓度: values.tpOut,
                    },
                    {
                      指标: '动植物油（mg/L）',
                      进水浓度: values.oilGreaseIn,
                      出水浓度: values.oilGreaseOut,
                    },
                    {
                      指标: '总大肠杆菌群数（个 / L）',
                      进水浓度: values.coliformTotalIn,
                      出水浓度: values.coliformTotalOut,
                    },
                  ],
                }),
                fenlei: values.industryType,
              },
            },
            ctrl1
          );
        },
        controller: new AbortController(),
      },
      {
        dependsOn: { removalData: 0 },
        component: (data: any, onDataChange: (newData: any) => void) => (
          <>
            <ActionCard>
              <RemovalTable
                data={data.removalData}
                onDataChange={onDataChange}
              ></RemovalTable>
            </ActionCard>
          </>
        ),
      },
      {
        dependsOn: { editedData: 1 },
        requester: (dependencies: Record<string, any>) => {
          console.log(dependencies);

          const ctrl2 = new AbortController();
          const editedData = dependencies.editedData; // 获取第一个请求的结果

          return sendDifyRequest(
            {
              query: '生成方案',
              auto_generate_name: true,
              inputs: {
                service: 'plan',
                water: values.designFlowRate,
                gongyi: flow?.aiAnalysisText,
                shejicanshu: JSON.stringify({
                  污染物: [
                    {
                      指标: 'pH',
                      进水浓度: values.phIn,
                      出水浓度: values.phOut,
                    },
                    {
                      指标: 'CODcr（mg/L）',
                      进水浓度: values.codcrIn,
                      出水浓度: values.codcrOut,
                    },
                    {
                      指标: 'BOD5（mg/L）',
                      进水浓度: values.bod5In,
                      出水浓度: values.bod5Out,
                    },
                    {
                      指标: 'SS（mg/L）',
                      进水浓度: values.ssIn,
                      出水浓度: values.ssOut,
                    },
                    {
                      指标: 'NH3-N（mg/L）',
                      进水浓度: values.nh3nIn,
                      出水浓度: values.nh3nOut,
                    },
                    {
                      指标: 'TN（mg/L）',
                      进水浓度: values.tnIn,
                      出水浓度: values.tpOut,
                    },
                    {
                      指标: 'TP（mg/L）',
                      进水浓度: values.tpIn,
                      出水浓度: values.tpOut,
                    },
                    {
                      指标: '动植物油（mg/L）',
                      进水浓度: values.oilGreaseIn,
                      出水浓度: values.oilGreaseOut,
                    },
                    {
                      指标: '总大肠杆菌群数（个 / L）',
                      进水浓度: values.coliformTotalIn,
                      出水浓度: values.coliformTotalOut,
                    },
                  ],
                }),
                fenlei: values.industryType,
              },
            },
            ctrl2
          );
        },
        controller: new AbortController(),
      },
    ];

    result.push({
      key: '公司名称',
      type: 'string',
      value: values.title,
    });

    result.push({
      key: '设计水量',
      type: 'number',
      value: values.designFlowRate,
    });

    result.push({
      key: '行业类型',
      type: 'string',
      value: values.industryType,
    });

    result.push({
      key: '进水浓度',
      type: 'object',
      value: {
        pH: values.phIn,
        CODcr: values.codcrIn,
        BOD5: values.bod5In,
        SS: values.ssIn,
        'NH3-N': values.nh3nIn,
        TN: values.tnIn,
        TP: values.tpIn,
        动植物油: values.animalOilIn,
        总大肠杆菌群数: values.coliformCountIn,
      },
    });

    result.push({
      key: '出水浓度',
      type: 'object',
      value: {
        pH: values.phOut,
        CODcr: values.codcrOut,
        BOD5: values.bod5Out,
        SS: values.ssOut,
        'NH3-N': values.nh3nOut,
        TN: values.tnOut,
        TP: values.tpOut,
        动植物油: values.animalOilOut,
        总大肠杆菌群数: values.coliformCountOut,
      },
    });

    onSubmit?.({
      parameters: result,
      request: requests,
      values,
    });

    docxRef.current = {
      ...docxRef.current,
      companyName: values.title,
      designFlowRate: values.designFlowRate,
      industryType: values.industryType,
    };
  };

  return (
    <>
      <Form
        className={clsx('my-4', className)}
        layout="vertical"
        onSubmit={handleSubmit}
        onSubmitFail={(error) => {
          console.log('验证失败', error);
        }}
        getFormApi={getFormApi}
      >
        <Card
          title="售前方案参数表"
          className="shadow-lg"
          style={{ borderRadius: '12px' }}
        >
          <div className="space-y-6">
            {/* 基本信息区域 */}
            <div className="rounded-lg border border-gray-200 bg-white p-6">
              <h3 className="mb-4 flex items-center text-lg font-semibold text-gray-800">
                <span className="mr-3 h-6 w-1 rounded bg-blue-500"></span>
                基本信息
              </h3>

              <Space wrap className="w-full">
                <div className="min-w-0 flex-1">
                  <Form.Input
                    field="title"
                    label="公司名称"
                    placeholder="请输入公司名称"
                    style={{
                      width: '100%',
                      minWidth: '300px',
                    }}
                    size="large"
                    rules={[
                      {
                        required: true,
                        message: '请输入公司名称',
                        min: 0,
                      },
                    ]}
                  />
                </div>

                <div className="min-w-0">
                  <Form.Input
                    field="designFlowRate"
                    label="设计水量"
                    type="number"
                    size="large"
                    rules={[
                      {
                        required: true,
                        message: '请输入设计水量',
                        min: 0,
                      },
                    ]}
                    placeholder="1000"
                    onChange={(value) => {
                      setDesignFlow(+value);
                    }}
                    width={200}
                    addonAfter="m³/d"
                  />
                </div>

                <div className="min-w-0">
                  <Form.Select
                    field="industryType"
                    label={{ text: '行业类型', optional: true }}
                    style={{ width: 200 }}
                    size="large"
                    initValue="slaughter"
                  >
                    <Form.Select.Option value="slaughter">
                      屠宰
                    </Form.Select.Option>
                    <Form.Select.Option value="user">大豆</Form.Select.Option>
                  </Form.Select>
                </div>
              </Space>
            </div>

            <Divider margin="24px" />

            <FlowSelectCard
              onChange={handleSelectChange}
              getAllFlows={handleAllFlows}
              selectedFlow={selectedFlow}
            ></FlowSelectCard>

            {/* 参数配置区域 */}
            <div className="rounded-lg border border-gray-200 bg-white p-6">
              <h3 className="mb-4 flex items-center text-lg font-semibold text-gray-800">
                <span className="mr-3 h-6 w-1 rounded bg-green-500"></span>
                设计参数配置
              </h3>

              <div className="overflow-x-auto">
                <Table
                  className="overflow-hidden rounded-lg shadow-md"
                  dataSource={listData}
                  pagination={false}
                  bordered
                  showHeader={false}
                  size="small"
                  columns={tableColumns}
                />
              </div>
            </div>
          </div>
        </Card>
        {children}
      </Form>
    </>
  );
}

export interface FetchRequestWithController {
  requester: () => Promise<
    FetchResponse<ReadableStream<Uint8Array<ArrayBufferLike>>>
  >;
  controller: AbortController;
}
